package com.yueqianshop.order.service.impl;

import com.alibaba.fastjson.TypeReference;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import com.yueqianshop.common.constant.OrderConstant;
import com.yueqianshop.common.exception.NoStockException;
import com.yueqianshop.common.to.OrderTo;
import com.yueqianshop.common.to.SeckillOrderTo;
import com.yueqianshop.common.to.SkuHasStockVo;
import com.yueqianshop.common.utils.R;
import com.yueqianshop.common.vo.MemberRespVo;
import com.yueqianshop.order.entity.OrderItemEntity;
import com.yueqianshop.order.enume.OrderStatusEnum;
import com.yueqianshop.order.feign.CartFeignService;
import com.yueqianshop.order.feign.MemberFeignService;
import com.yueqianshop.order.feign.ProductFeignService;
import com.yueqianshop.order.feign.WareFeignService;
import com.yueqianshop.order.interceptor.LoginUserInterceptor;
import com.yueqianshop.order.service.OrderItemService;
import com.yueqianshop.order.to.OrderCreateTo;
import com.yueqianshop.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yueqianshop.common.utils.PageUtils;
import com.yueqianshop.common.utils.Query;

import com.yueqianshop.order.dao.OrderDao;
import com.yueqianshop.order.entity.OrderEntity;
import com.yueqianshop.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo orderConfirm() throws ExecutionException, InterruptedException {

        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //获取主线程的请求头数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> addressFutrue = CompletableFuture.runAsync(() ->{
            // 将主线程的请求头数据带到异步执行的线程中进行共享，解决异步调用丢失请求头问题
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1、设置收货地址
            List<MemberAddressVo> memberAddress = memberFeignService.getMemberAddress(memberRespVo.getId());
            orderConfirmVo.setAddress(memberAddress);
        },executor);

        CompletableFuture<Void> cartItemsFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2、设置购物车选中的购物项，远程查询购物车选中的购物项
            List<OrderItemVo> items = cartFeignService.getCheckedCartItem();
            orderConfirmVo.setItems(items);
        },executor).thenRunAsync(() -> {
            //远程查询库存的商品状态
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIds = items.stream().map((item) -> item.getSkuId()).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasStock(skuIds);
            List<SkuHasStockVo> skuHasStockVos = r.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            if(skuHasStockVos != null){
                Map<Long, Boolean> stocks = skuHasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId,SkuHasStockVo::getHasStock));
                orderConfirmVo.setStocks(stocks);
            }
        },executor);



        ;

        //3、设置会员积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //4、设置订单总额和应付总额，通过计算直接设置


        //5、设置防重令牌
        String token = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(OrderConstant.MEMBER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);

        CompletableFuture.allOf(addressFutrue,cartItemsFuture).get();
        return orderConfirmVo;
    }

    //提交订单
    @Transactional
    @Override
    public OrderSubmitResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderSubmitResponseVo orderSubmitResponseVo = new OrderSubmitResponseVo();
        orderSubmitResponseVo.setCode(0);
        orderSubmitVoThreadLocal.set(orderSubmitVo);

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVo.getOrderToken();
        Long code = (Long) redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.MEMBER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);
        if(code == 0L){// 令牌验证失败
            orderSubmitResponseVo.setCode(1);
            return orderSubmitResponseVo;
        }else{
            OrderCreateTo orderCreateTo = createOrder();
            BigDecimal payAmount = orderCreateTo.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if (Math.abs((payAmount.subtract(payPrice)).doubleValue()) < 0.01){

                //验价通过，保存订单
                saveOrder(orderCreateTo);
                //锁库存
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(orderCreateTo.getOrder().getOrderSn());
                List<OrderItemVo> orderItems = orderCreateTo.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItems);
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if(r.getCode() == 0){
                    //锁成功l
                    orderSubmitResponseVo.setOrder(orderCreateTo.getOrder());

                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.exchange", orderCreateTo.getOrder());
                }else{
                    //锁失败
                    throw new NoStockException((String) r.get("msg"));
                }
                return orderSubmitResponseVo;
            }else {
                //金额对比失败
                orderSubmitResponseVo.setCode(2);
                return orderSubmitResponseVo;
            }


        }

    }

    /**
     * 通过订单号查询订单
     * @param orderSn
     * @return
     */
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    /**
     * 关闭订单
     * @param orderEntity
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        OrderEntity order = baseMapper.selectById(orderEntity.getId());
        if(order.getStatus() == 0){
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(4);
            baseMapper.updateById(update);

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order, orderTo);
            try{
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }



    /**
     * 保存订单
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        //1、保存订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        this.save(order);
        //2、保存所有订单数据
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        orderItemService.saveBatch(orderItems);


    }


    //创建订单
    private OrderCreateTo createOrder(){
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //设置订单号
        String orderSn = IdWorker.getTimeId();
        //1、订单消息 获取订单代码抽取为buildOrder方法
        OrderEntity order = buildOrder(orderSn);
        orderCreateTo.setOrder(order);
        //2、获取所有的订单项
        List<OrderItemEntity> orderItems = buildOrderItems(orderSn);
        orderCreateTo.setOrderItems(orderItems);
        //3、计算价格、积分等相关
        computeAmount(order,orderItems);
        return orderCreateTo;
    }

    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    //构建订单数据
    private OrderEntity buildOrder(String orderSn){
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();
        OrderEntity order = new OrderEntity();
        //1、设置订单、下单时间
        order.setOrderSn(orderSn);
        order.setCreateTime(new Date());
        //2、设置收货信息
        //远程调用获取收货地址信息
        R r = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = r.getData(new TypeReference<FareVo>() {
        });
        //设置运费信息
        order.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        order.setReceiverCity(fareResp.getAddress().getCity());
        order.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        order.setReceiverName(fareResp.getAddress().getName());
        order.setReceiverPhone(fareResp.getAddress().getPhone());
        order.setReceiverPostCode(fareResp.getAddress().getPostCode());
        order.setReceiverRegion(fareResp.getAddress().getRegion());

        //3、设置订单状态信息
        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        order.setAutoConfirmDay(7);
        order.setDeleteStatus(0);

        //4、设置会员信息
        order.setMemberId(LoginUserInterceptor.loginUser.get().getId());
        return order;

    }

    //构建所有订单项数据
    private List<OrderItemEntity> buildOrderItems(String orderSn){
        //最后一次确定购物项价格
        List<OrderItemVo> checkedCartItem = cartFeignService.getCheckedCartItem();
        if (checkedCartItem != null && checkedCartItem.size() > 0){
            List<OrderItemEntity> orderItems = checkedCartItem.stream().map((orderItemVo) -> {
                OrderItemEntity orderItem = buildOrderItem(orderItemVo);
                orderItem.setOrderSn(orderSn);
                return orderItem;
            }).collect(Collectors.toList());
            return orderItems;
        }
        return null;
    }

    //构建某一个订单项数据
    private OrderItemEntity buildOrderItem(OrderItemVo orderItemVo){
        OrderItemEntity orderItem = new OrderItemEntity();

        R r = productFeignService.getSpuInfoBySkuId(orderItemVo.getSkuId());
        SpuInfoVo spuInfo = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItem.setSpuBrand(spuInfo.getBrandId().toString());
        orderItem.setSpuId(spuInfo.getId());
        orderItem.setSpuName(spuInfo.getSpuName());
        orderItem.setCategoryId(spuInfo.getCatalogId());

        orderItem.setSkuId(orderItemVo.getSkuId());
        orderItem.setSkuName(orderItemVo.getTitle());
        orderItem.setSkuPic(orderItemVo.getImage());
        orderItem.setSkuPrice(orderItemVo.getPrice());

        orderItem.setSkuQuantity(orderItemVo.getCount());

        orderItem.setSkuAttrsVals(StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttr(),";"));

        orderItem.setGiftGrowth(orderItemVo.getPrice().intValue());
        orderItem.setGiftIntegration(orderItemVo.getPrice().intValue());

        orderItem.setPromotionAmount(new BigDecimal("0"));
        orderItem.setCouponAmount(new BigDecimal("0"));
        orderItem.setIntegrationAmount(new BigDecimal("0"));

        BigDecimal originPrice = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuQuantity().toString()));
        BigDecimal realAmount = originPrice.subtract(orderItem.getPromotionAmount()).subtract(orderItem.getCouponAmount()).subtract(orderItem.getIntegrationAmount());

        orderItem.setRealAmount(realAmount);

        return orderItem;


    }

    //统计总额信息
    private void computeAmount(OrderEntity order, List<OrderItemEntity> orderItems){
        // 订单总额
        BigDecimal totalAmount = new BigDecimal("0");
        // 促销优惠总额
        BigDecimal promotionAmount = new BigDecimal("0");
        // 优惠券优惠总额
        BigDecimal couponAmount = new BigDecimal("0");
        // 积分优惠总额
        BigDecimal integrationAmount = new BigDecimal("0");
        // 用户可获得的总成长值
        Integer giftGrowthAmount = 0;
        // 用户可获得的总积分
        Integer giftIntegrationAmount = 0;
        for (OrderItemEntity orderItem : orderItems) {
            totalAmount = totalAmount.add(orderItem.getRealAmount());
            promotionAmount = promotionAmount.add(orderItem.getPromotionAmount());
            couponAmount = couponAmount.add(orderItem.getCouponAmount());
            integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount());
            giftGrowthAmount = giftGrowthAmount + orderItem.getGiftGrowth();
            giftIntegrationAmount = giftIntegrationAmount + orderItem.getGiftIntegration();
        }
        order.setTotalAmount(totalAmount);
        order.setPayAmount(totalAmount.add(order.getFreightAmount())); // 应付总额(订单总额+运费)
        order.setPromotionAmount(promotionAmount);
        order.setCouponAmount(couponAmount);
        order.setIntegrationAmount(integrationAmount);
        order.setGrowth(giftGrowthAmount);
        order.setIntegration(giftIntegrationAmount);

    }

    /**
     * 计算商品支付需要的信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo payOrder(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
        //向上取整两位数
        BigDecimal decimal = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(decimal.toString());
        payVo.setOut_trade_no(orderSn);
        List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = itemEntities.get(0);
        payVo.setSubject(itemEntity.getSkuName());
        payVo.setBody(itemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> orders = page.getRecords().stream().map((order) -> {
            List<OrderItemEntity> orderItems = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setOrderItems(orderItems);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(orders);

        return new PageUtils(page);
        

    }

    @Override
    public void saveSeckillOrder(SeckillOrderTo seckillOrderTo) {
        // 1、保存订单详细信息
        OrderEntity order = new OrderEntity();
        order.setCreateTime(new Date());
        order.setOrderSn(seckillOrderTo.getOrderSn());
        order.setMemberId(seckillOrderTo.getMemberId());
        order.setStatus(0);
        order.setPayAmount(seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum())));
        // 2、保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setRealAmount(seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum())));
        orderItem.setOrderSn(seckillOrderTo.getOrderSn());
        orderItem.setSkuQuantity(seckillOrderTo.getNum());
        //TODO 远程查询商品sku信息
        //TODO 远程查询会员收获地址相关信息

        this.save(order);
        orderItemService.save(orderItem);
    }


}